package com.ky.pro.java.concurrency;

import static com.ky.pro.java.concurrency.algo.FiboUtil.fibo;

/**
 * @ClassName MonitorMain
 * @Description 使用synchronized + wait/notify机制实现
 * @Date 2021/11/23 22:32
 * @Author kevin
 **/
public class MonitorMain {

    public static void main(String[] args) throws InterruptedException {

        long start = System.currentTimeMillis();

        // 在这里创建一个线程或线程池，
        // 异步执行 下面方法

        Object objLock = new Object();

        Integer result = 0;
        FiboMonitorTask task = new FiboMonitorTask(objLock);

        new Thread(task).start();

        synchronized (objLock) {
            objLock.wait();
        }

        // 确保  拿到result 并输出
        System.out.println("异步计算结果为：" + task.getResult());

        System.out.println("使用时间：" + (System.currentTimeMillis() - start) + " ms");

        // 然后退出main线程

    }

    static class FiboMonitorTask implements Runnable {

        private int result;

        private Object lock;

        public FiboMonitorTask(Object lock) {
            this.lock = lock;
        }

        @Override
        public void run() {
            synchronized (lock) {
                result = fibo(36);
                lock.notifyAll();
            }
        }

        public int getResult() {
            return result;
        }
    }

}
